#!/usr/bin/env python
# coding=utf-8
from http.server import HTTPServer, BaseHTTPRequestHandler
from urllib import parse
from queue import Queue,Empty
import threading
from iptopv2 import exporter


class Producer(threading.Thread):
    def __init__(self, name,queue):
        threading.Thread.__init__(self, name=name)
        self.data=queue

    def run(self):
        exporter(self.data,10)
        print("%s finished!" % self.getName())

class Consumer(threading.Thread):
    def __init__(self,name,queue):
        threading.Thread.__init__(self,name=name)
        self.data=queue
    def run(self):
        start_server(self.data)
        print("%s finished!" % self.getName())
old =""

def start_server(que:Queue):
    host = ('localhost', 9100)
    
    class HttpHandler(BaseHTTPRequestHandler):
        def do_GET(self):
            _,_, path,_,_=parse.urlsplit(self.path)
            self._response(path)

        def do_POST(self):
            self._response(self.path)
            
        def _response(self, path):
            code=200
            rtv=""
            global old
            if path=="/metrics":
                try:
                    q = que.get_nowait()
                    rtv +="# HELP netflow_recv recv bytes of http api requests\n# TYPE netflow_recv gauge\n"
                    for  v in q.recvs:
                    # 'pid','comm','sport', 'addr', 'dport',"type","bytes"
                        rtv += f'netflow_recv{{pid="{v.pid}",comm="{v.comm}",sport="{v.sport}",addr="{v.addr}",dport="{v.dport}",type="{v.type}"}} {float(v.byteVal)}\n'
                    rtv +="# HELP netflow_send send bytes of http api requests\n# TYPE netflow_send gauge\n"
                    for v in q.sends:
                        rtv += f'netflow_send{{pid="{v.pid}",comm="{v.comm}",sport="{v.sport}",addr="{v.addr}",dport="{v.dport}",type="{v.type}"}} {float(v.byteVal)}\n'
                    rtv +="# HELP netflow_total sum bytes of http api requests\n# TYPE netflow_total gauge\n"
                    rtv += f'netflow_total{{type="total"}} {float(q.totals[2])}\nnetflow_total{{type="send"}} {float(q.totals[1])}\nnetflow_total{{type="recv"}} {float(q.totals[0])}\n'
                    old = rtv
                except Empty:
                    if old!="":
                        rtv =old

                


            else:
                print(path)
                code=404
                rtv+= f"404路径{path}不存在"
            self.send_response(code)
            self.send_header('Content-type', 'text/json; charset=utf-8')
            self.send_header('Access-Control-Allow-Origin', '*')
            self.end_headers()
            self.wfile.write(rtv.encode())
    server = HTTPServer(host, HttpHandler)
    print("Starting server, listen at: %s:%s" % host)
    server.serve_forever()

if __name__ == '__main__':
    print("start server success...")
    queue = Queue()
    producer = Producer('Producer',queue)
    consumer = Consumer('Consumer',queue)

    producer.start()
    consumer.start()

    producer.join()
    consumer.join()

